package com.yoyo.itravel.utils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description 文件工具类
 *
 * @author HZX
 * @date 2020/5/10 16:14
 */
public class FileUtils {

    private FileUtils() {
    }

    /**
     * @param filePath
     * @throws FileNotFoundException
     * @Description 获得文件输入流
     */
    public static InputStream getFileInputStream(String filePath) throws FileNotFoundException {
        File file = new File(filePath);
        FileInputStream in = new FileInputStream(file);

        return in;
    }

    /**
     * @Description 功能:压缩多个文件成一个zip文件
     *
     * @param srcfile：源文件列表
     * @param zipfile：压缩后的文件
     * @throws Exception
     */
    public static void zipFiles(String[] srcfile, String[] localName, File zipfile) throws Exception {
        byte[] buf = new byte[1024];
        //ZipOutputStream类：完成文件或文件夹的压缩
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
        InputStream in = null;
        for (int i = 0; i < srcfile.length; i++) {
            try {
                in = getFileInputStream(srcfile[i]);
                out.putNextEntry(new ZipEntry(localName[i]));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (in != null) {
                    in.close();
                    in = null;
                }
                continue;
            }
        }
        out.close();
        System.out.println("压缩完成.");
    }

}
